<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class Order extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Usermodel');
        $this->load->model('Ordermodel');
        $this->load->helper('url');
        $this->load->library('myauth');
        // $this->output->enable_profiler(TRUE);
    }

    public function check_in($pid=0) {
        if ($this->myauth->execute_auth() == false) { 
            echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
            $url = site_url('login');
            echo "<script language='javascript' >alert('魂淡!登录去!');location.replace('$url');</script>";
        }
        else{
            $uid = $this->session->userdata('uid');
            $ret = $this->Usermodel->user_detail($uid);
            if($pid!=0&&$ret[0][$pid]==0){
                  echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
                  $url = site_url('login');
                  echo "<script language='javascript' >alert('对不起，您没有该权限');location.replace('$url');</script>";
                  return;
            }
            return $ret[0];
        }
    }

    //跳转到有权限的页面
    public function index() {
        $data['ret'] = $this->check_in();
        $data['is_admin'] = $this->myauth->check_permission('p6');
        if($data['ret']['p1']){
            redirect('order/new_order');
        }
         if($data['ret']['p2']){
            redirect('order/wait_for_pay');
        }       
        if($data['ret']['p3']){
            redirect('order/wait_for_buy');
        }
        if($data['ret']['p4']){
            redirect('order/wait_for_delivery');
        }  
        if($data['ret']['p5']){
            redirect('order/order_allocation');
        }
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        $url = site_url('login');
        echo "<script language='javascript' >alert('您没啥权限啊，和管理员说下呗!');location.replace('$url');</script>";
        return;
    }

    public function new_order() {
        $data['ret'] = $this->check_in('p1');
        $data['is_admin'] = $this->myauth->check_permission('p6');
        $this->load->view('new_order.php', $data);
    }

    //插入一些测试数据,测试分页类
    public function test_data() {
        for ($i = 0; $i < 1000; $i++) {
            $order_array = array(
                'orderNumber' => $i + 33000,
                'orderTime' => '2012-11-1',
                'postcode' => $i + 33000,
                'clientName' => '赵王军',
                'clientPhone' => '15158131797',
                'clientAddress' => '杭州',
                'paymentMethod' => '信用卡',
                'state' => 0
            );
            $orderid = $this->Ordermodel->insert_order($order_array);
            $commodity_array = array(
                'orderId' => $orderid,
                'commodityNumber' => $i + 33000,
                'imagePath' => '/uploads/2012_11_03_03_11_37_26.jpg',
                'link' => 'http://www.baidu.com',
                'colorAndSize' => 'L and Blue',
                'amount' => $i,
                'unitPrice' => 12.121,
            );
            $this->Ordermodel->insert_commodity($commodity_array);
        }
    }

    public function order_insert() {
        if (isset($_POST['orderNumber'])) {
            try {
                $order_array = array(
                    'orderNumber' => $_POST['orderNumber'],
                    'orderTime' => $_POST['orderTime'],
                    'postcode' => $_POST['postcode'],
                    'clientName' => $_POST['clientName'],
                    'clientPhone' => $_POST['clientPhone'],
                    'clientAddress' => $_POST['clientAddress'],
                    'paymentMethod' => $_POST['paymentMethod'],
                    'total' => $_POST['total_mount'],
                    'deliveryMoney' => $_POST['freight'],
                    'state' => 0
                );
                if (!empty($_POST['cashEntryTime'])) {
                    $order_array['cashEntryTime'] = $_POST['cashEntryTime'];
                    $order_array['state'] = 1;
                }
//                if (isset($_POST['cashEntryTime']))
//                    $order_array['cashEntryTime'] = $_POST['cashEntryTime'];
                $ret = $this->db->from('orders')->where('orderNumber', $_POST['orderNumber'])->get()->num_rows;
                if ($ret > 0) {
                    echo 'error';
                    return;
                }
                $orderid = $this->Ordermodel->insert_order($order_array);
                for ($index = 0; $index < $_POST['all_kinds']; $index++) {
                    if (isset($_POST['commodityNumber'][$index])) {
                        $commodity_array = array(
                            'orderId' => $orderid,
                            'commodityNumber' => $_POST['commodityNumber'][$index],
                            'imagePath' => $_POST['img_name'][$index],
                            'link' => $_POST['link'][$index],
                            'colorAndSize' => $_POST['colorAndSize'][$index],
                            'amount' => $_POST['amount'][$index],
                            'unitPrice' => $_POST['unitPrice'][$index],
                        );
                        $this->Ordermodel->insert_commodity($commodity_array);
                    }
                }
                echo "success";
            } catch (Exception $e) {
                show_error($e->getMessage());
                echo "error";
            }
        }
    }

    //列出未入账状态订单
    function wait_for_pay() {
        $data['ret'] = $this->check_in('p2');
        $data['is_admin'] = $this->myauth->check_permission('p6');
        $config['base_url'] = site_url() . '/order/wait_for_pay';
        $config['total_rows'] = $this->Ordermodel->wait_for_pay_order_num();
        $config['num_links'] = 5;
        $config['per_page'] = 10;
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';
        $config['first_link'] = '第一页';
        $config['last_link'] = '尾页';
        $this->pagination->initialize($config);

        $data['ids'] = $this->Ordermodel->wait_for_pay_ids($config['per_page'], $this->uri->segment(3));

        $IdSet = array();
        foreach ($data['ids'] as $key => $value) {
            foreach ($value as $key2 => $value2) {
                $IdSet[] = $value2;
            }
        }
        $num = $this->uri->segment(3);
        if (empty($num))
            $num = 0;

        if (!empty($IdSet)) {
            $data['list'] = $this->Ordermodel->wait_for_pay_order_list($IdSet);
            $data['num'] = $num;
            $this->load->view('wait_for_pay', $data);
        } else {
            $data['list'] = array();
            $data['num'] = $num;
            $this->load->view('wait_for_pay', $data);
        }
    }

    //改变未入账状态
    function wait_for_pay_update() {
        $data = $this->input->post();
        $index = 0;
        $id = null;
        $date = null;
        foreach ($data as $key => $value) {
            if ($index % 2 == 0)
                $id = $value;
            else {
                $date = $value;
                $this->Ordermodel->wait_for_pay_update($id, $date);
            }
            $index++;
        }
        $url = site_url("order/wait_for_pay/" . $this->uri->segment(3));
        $msg = "确认入账成功";
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        echo "<script language='javascript' >alert('$msg');location.replace('$url');</script>";
    }

    //未采购、已采购状态订单
    function wait_for_buy() {
        $data['ret'] = $this->check_in('p3');
        $data['is_admin'] = $this->myauth->check_permission('p6');
        $config['base_url'] = site_url() . '/order/wait_for_buy';
        $config['total_rows'] = $this->Ordermodel->wait_for_buy_order_num();
        $config['num_links'] = 5;
        $config['per_page'] = 10;
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';
        $config['first_link'] = '第一页';
        $config['last_link'] = '尾页';
        $this->pagination->initialize($config);

        $data['ids'] = $this->Ordermodel->wait_for_buy_ids($config['per_page'], $this->uri->segment(3));

        $IdSet = array();
        foreach ($data['ids'] as $key => $value) {
            foreach ($value as $key2 => $value2) {
                $IdSet[] = $value2;
            }
        }
        $cnum = $this->uri->segment(3);
        if (empty($cnum))
            $cnum = 0;

        if (!empty($IdSet)) {
            //循环最多执行两次
            while (true) {
                $data['list'] = $this->Ordermodel->wait_for_buy($IdSet);

                $pre = -1;
                $num = 0;
                $count = 0;
                $state = 3;
                $flag = true;

                foreach ($data['list'] as $key => $value) {
                    if ($value['id'] == $pre) {
                        $count++;
                        if (isset($value['procureNumber'])) {
                            $num++;
                        }
                    } else {
                        if ($state == 1) {
                            if ($count == $num) {
                                $flag = false;
                                $this->Ordermodel->wait_for_buy_to_state2($pre);
                            }
                        } else if ($state == 2) {
                            if ($count != $num) {
                                $flag = false;
                                $this->Ordermodel->wait_for_buy_to_state1($pre);
                            }
                        }
                        $pre = $value['id'];
                        $count = 0;
                        $num = 0;
                        $state = $value['state'];
                        $count++;
                        if (isset($value['procureNumber'])) {
                            $num++;
                        }
                    }
                }
                if ($state == 1) {
                    if ($count == $num) {
                        $flag = false;
                        $this->Ordermodel->wait_for_buy_to_state2($pre);
                    }
                } else if ($state == 2) {
                    if ($count != $num) {
                        $flag = false;
                        $this->Ordermodel->wait_for_buy_to_state1($pre);
                    }
                }
                if ($flag)
                    break;
            }
            $data['num'] = $cnum;
            $this->load->view('wait_for_buy', $data);
        } else {
            $data['list'] = array();
            $data['num'] = $cnum;
            $this->load->view('wait_for_buy', $data);
        }
    }

    //确认已配货，将已采购状态更改为已配货
    function wait_for_buy_update_confirm() {
        $data = $this->input->post();
        foreach ($data as $key => $value) {
            $this->Ordermodel->wait_for_buy_update_confirm($value);
        }
        $url = site_url("order/wait_for_buy/" . $this->uri->segment(3));
        $msg = "确认配货成功";
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        echo "<script language='javascript' >alert('$msg');location.replace('$url');</script>";
    }

    //操作商品信息
    function wait_for_buy_commodity() {
        $data['commodity'] = $this->Ordermodel->wait_for_buy_commodity($this->uri->segment(3));
        $data['num'] = $this->uri->segment(4);
        $this->load->view('wait_for_buy_commodity', $data);
    }

    //将对商品的更改信息保存下来
    function wait_for_buy_commodity_save() {
        $data = $this->input->post();
        $id = $this->uri->segment(3);

        $update = array(
            'procurement' => $data['procurement'],
            'procureNumber' => $data['procureNumber'],
            'procureTime' => $data['procureTime'],
            'procureAmount' => $data['procureAmount'],
            'procureUnitPrice' => $data['procureUnitPrice'],
            'procureFreight' => $data['procureFreight'],
            'procureMoney' => $data['procureMoney']
        );
        $this->Ordermodel->wait_for_buy_commodity_update($id, $update);

        $url = site_url("order/wait_for_buy/" . $this->uri->segment(4));
        $msg = "保存信息成功";
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        echo "<script language='javascript'>alert('$msg');location.replace('$url');</script>";
    }

    //将采购信息删除
    function wait_for_buy_commodity_abandon() {
        $data = array(
            'procurement' => null,
            'procureNumber' => null,
            'procureTime' => null,
            'procureAmount' => null,
            'procureUnitPrice' => null,
            'procureFreight' => null,
            'procureMoney' => null,
        );
        $id = $this->uri->segment(3);
        $this->Ordermodel->wait_for_buy_commodity_update($id, $data);

        $url = site_url("order/wait_for_buy/" . $this->uri->segment(4));
        $msg = "删除采购信息成功";
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        echo "<script language='javascript' >alert('$msg');location.replace('$url');</script>";
    }

    //列出已配货待发货订单
    function wait_for_delivery() {
        $data['ret'] = $this->check_in('p4');
        $data['is_admin'] = $this->myauth->check_permission('p6');
        $config['base_url'] = site_url() . '/order/wait_for_delivery';
        $config['total_rows'] = $this->Ordermodel->wait_for_delivery_num();
        $config['num_links'] = 5;
        $config['per_page'] = 10;
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';
        $config['first_link'] = '第一页';
        $config['last_link'] = '尾页';
        $this->pagination->initialize($config);

        $data['ids'] = $this->Ordermodel->wait_for_delivery_ids($config['per_page'], $this->uri->segment(3));
        $IdSet = array();
        foreach ($data['ids'] as $key => $value) {
            foreach ($value as $key2 => $value2) {
                $IdSet[] = $value2;
            }
        }
        $num = $this->uri->segment(3);
        if (empty($num))
            $num = 0;

        if (!empty($IdSet)) {
            $data['list'] = $this->Ordermodel->wait_for_delivery($IdSet);
            $data['num'] = $num;
            $this->load->view('wait_for_delivery', $data);
        } else {
            $data['list'] = array();
            $data['num'] = $num;
            $this->load->view('wait_for_delivery', $data);
        }
    }

    //更新配货信息
    function wait_for_delivery_alter() {
        $data = NULL;
        $data = $this->Ordermodel->wait_for_delivery_alter($this->uri->segment(3));
        $data['num'] = $this->uri->segment(4);
        $this->load->view('wait_for_delivery_alter', $data);
    }

    //添加配货信息
    function wait_for_delivery_add() {
        $data = NULL;
        $data = $this->Ordermodel->wait_for_delivery_add($this->uri->segment(3));
        $data['num'] = $this->uri->segment(4);
        $this->load->view('wait_for_delivery_add', $data);
    }

    //确认已发货
    function wait_for_delivery_confirm() {
        $data = $this->input->post();
        foreach ($data as $key => $value) {
            $this->Ordermodel->wait_for_delivery_update($value);
        }
        $url = site_url("order/wait_for_delivery/" . $this->uri->segment(3));
        $msg = "确认已发货成功";
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        echo "<script language='javascript' >alert('$msg');location.replace('$url');</script>";
    }

    //保存发货信息
    function wait_for_delivery_save() {
        $data = $this->input->post();
        $add = array("deliveryTime" => $data['deliveryTime'],
            'expressNumber' => $data['expressNumber'],
            'expressMethod' => $data['expressMethod'],
            'weight' => $data['weight'],
            'actualFreight' => $data['actualFreight'],
            'expressComment' => $data['expressComment'],
            'clientComment' => $data['clientComment'],
            'orderId' => $data['id']);
        $this->db->insert('delivery', $add);

        $url = site_url("order/wait_for_delivery/" . $this->uri->segment(3));
        $msg = "添加成功";
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        echo "<script language='javascript' >alert('$msg');location.replace('$url');</script>";
    }

    //保存修改之后的发货信息
    function wait_for_delivery_alter_save() {
        $data = $this->input->post();
        $add = array("deliveryTime" => $data['deliveryTime'],
            'expressNumber' => $data['expressNumber'],
            'expressMethod' => $data['expressMethod'],
            'weight' => $data['weight'],
            'actualFreight' => $data['actualFreight'],
            'expressComment' => $data['expressComment'],
            'clientComment' => $data['clientComment'],);
        $this->db->where('orderId', $data['id']);
        $this->db->update('delivery', $add);

        $url = site_url("order/wait_for_delivery/" . $this->uri->segment(3));
        $msg = "更新成功";
        echo "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>";
        echo "<script language='javascript' >alert('$msg');location.replace('$url');</script>";
    }

    //列出已发货状态订单
    function order_allocation() {
        $data['ret'] = $this->check_in('p5');
        $data['is_admin'] = $this->myauth->check_permission('p6');
        $config['base_url'] = site_url() . '/order/order_allocation';
        $config['total_rows'] = $this->Ordermodel->order_allocation_order_num();
        $config['num_links'] = 5;
        $config['per_page'] = 10;
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';
        $config['first_link'] = '第一页';
        $config['last_link'] = '尾页';
        $this->pagination->initialize($config);

        $data['ids'] = $this->Ordermodel->order_allocation_ids($config['per_page'], $this->uri->segment(3));
        $IdSet = array();
        foreach ($data['ids'] as $key => $value) {
            foreach ($value as $key2 => $value2) {
                $IdSet[] = $value2;
            }
        }
        if (!empty($IdSet)) {
            $data['list'] = $this->Ordermodel->allocated_orders($IdSet);
            $this->load->view('order_allocation', $data);
        } else {
            $data['list'] = array();
            $this->load->view('order_allocation', $data);
        }
    }

    function commodity_manage() {
        $this->load->view('commodity.php');
    }

    function commodity_list() {
        $page = $_POST['page'];
        $rp = $_POST['rp'];
        $sortname = $_POST['sortname'];
        $sortorder = $_POST['sortorder'];

        if (!$sortname)
            $sortname = 'name';
        if (!$sortorder)
            $sortorder = 'desc';
        if ($_POST['query'] != '') {
            $where = "WHERE `" . $_POST['qtype'] . "` LIKE '%" . $_POST['query'] . "%' ";
        } else {
            $where = '';
        }
        $sort = "ORDER BY $sortname $sortorder";

        if (!$page)
            $page = 1;
        if (!$rp)
            $rp = 10;

        $start = (($page - 1) * $rp);

        $limit = "LIMIT $start, $rp";
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-type: text/x-json");
        $sql = "SELECT id,iso,name,printable_name,iso3,numcode FROM country $where $sort $limit";
        $query = $this->db->query($sql);
        $total = $this->db->from('country')->count_all_results();
        $json = "";
        $json .= "{\n";
        $json .= "page: $page,\n";
        $json .= "total: $total,\n";
        $json .= "rows: [";
        $rc = false;
        foreach ($query->result_array() as $row) {
            if ($rc)
                $json .= ",";
            $json .= "\n{";
            $json .= "id:'" . $row['id'] . "',";
            $json .= "cell:['" . $row['id'] . "','" . $row['iso'] . "'";
            $json .= ",'" . addslashes($row['name']) . "'";
            $json .= ",'" . addslashes($row['printable_name']) . "'";
            $json .= ",'" . addslashes($row['iso3']) . "'";
            $json .= ",'" . addslashes($row['numcode']) . "']";
            $json .= "}";
            $rc = true;
        }
        $json .= "]\n";
        $json .= "}";
        echo $json;
    }

}

